package com.ruoyi.express.service.task;

import com.ruoyi.express.domain.BaiduApiToken;
import com.ruoyi.express.service.IBaiduApiTokenService;
import com.ruoyi.express.third.BaiduSupport;
import com.ruoyi.express.third.dto.TokenInput;
import com.ruoyi.express.third.dto.TokenResult;
import com.ruoyi.express.third.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 刷新百度开放平台access_token
 *
 * @author chenck
 * @date 2019/3/9 15:44
 */
@Component("refreshBaiduAccessToken")
public class RefreshBaiduAccessTokenTask {

    private static Logger LOGGER = LoggerFactory.getLogger(RefreshBaiduAccessTokenTask.class);

    @Value("${baidu.api.client_id}")
    String client_id;

    @Value("${baidu.api.client_secret}")
    String client_secret;

    @Value("${baidu.api.get_token_url}")
    String get_token_url;

    @Resource
    IBaiduApiTokenService iBaiduApiTokenService;

    /**
     * 刷新百度开放平台access_token
     *
     * @param
     * @return
     * @author chenck
     * @date 2019/3/9 15:46
     */
    public void refreshAccessToken() {
        BaiduApiToken baiduApiToken = iBaiduApiTokenService.selectBaiduApiTokenByClientId(client_id);
        if (null != baiduApiToken && null != baiduApiToken.getAccessTokenTime()) {
            // 计算access_token有效时间，并提前一天
            Date tokenEndTime = DateUtil.addDate(baiduApiToken.getAccessTokenTime(), -1, 0, baiduApiToken.getExpiresIn().intValue());
            Date now = new Date();

            // 判断access_token是否过期
            if (DateUtil.diffTwoDateWithTime(tokenEndTime, now) >= 0) {
                LOGGER.warn("client_id={}的access_token下次刷新时间为{}，现无需刷新", client_id, DateUtil.dateToStr(tokenEndTime, DateUtil.DEFUALT_LONG_TIME_FORMAT));
                return;
            }
            LOGGER.warn("client_id={}的access_token下次刷新时间为{}，现从百度获取token信息", client_id, DateUtil.dateToStr(tokenEndTime, DateUtil.DEFUALT_LONG_TIME_FORMAT));
        } else {
            LOGGER.warn("client_id={}的access_token数据不存在，现从百度获取token信息", client_id);
        }

        TokenInput input = new TokenInput(client_id, client_secret);
        input.setUrl(get_token_url);
        TokenResult result = BaiduSupport.call(input);

        if (null == baiduApiToken) {
            baiduApiToken = new BaiduApiToken();
            baiduApiToken.setCreateTime(new Date());
        }
        baiduApiToken.setClientId(client_id);
        baiduApiToken.setAccessToken(result.getAccess_token());
        baiduApiToken.setExpiresIn(result.getExpires_in());
        baiduApiToken.setAccessTokenTime(new Date());
        baiduApiToken.setRefreshToken(result.getRefresh_token());
        baiduApiToken.setScope(result.getScope());
        baiduApiToken.setSessionKey(result.getSession_key());
        baiduApiToken.setSessionSecret(result.getSession_secret());
        baiduApiToken.setUpdateTime(baiduApiToken.getAccessTokenTime());

        // 保存token信息
        if (baiduApiToken.getTokenId() == null) {
            iBaiduApiTokenService.insertBaiduApiToken(baiduApiToken);
        } else {
            iBaiduApiTokenService.updateBaiduApiToken(baiduApiToken);
        }
    }

}
